package com.compass.mobile.ui.fragment

import UserInfoManager
import android.annotation.SuppressLint
import android.os.Bundle
import android.view.View
import androidx.fragment.app.viewModels
import androidx.leanback.widget.ArrayObjectAdapter
import androidx.leanback.widget.BaseGridView
import androidx.leanback.widget.FocusHighlight
import androidx.leanback.widget.FocusHighlightHelper
import com.compass.mobile.R
import com.compass.mobile.callback.OnCustomButtonClick
import com.compass.mobile.callback.OnItemClickListener
import com.compass.mobile.databinding.FragmentCaseItemBinding
import com.compass.mobile.framework.base.BaseVBFragment
import com.compass.mobile.framework.constant.BACKSPACE_ACTION
import com.compass.mobile.framework.constant.CANCEL_ACTION
import com.compass.mobile.framework.constant.CASE_REPORT_ACTION
import com.compass.mobile.framework.constant.CLINICAL_RECEPTION
import com.compass.mobile.framework.constant.DETAILS_ACTION
import com.compass.mobile.framework.constant.END_ACTION
import com.compass.mobile.framework.constant.EVALUATION_ACTION
import com.compass.mobile.framework.constant.INQUIRY_ACTION
import com.compass.mobile.framework.constant.INSPECT_ACTION
import com.compass.mobile.framework.constant.LOCAL_PHONE
import com.compass.mobile.framework.constant.PRESCRIPTION_ACTION
import com.compass.mobile.framework.constant.REFERRAL_ACTION
import com.compass.mobile.framework.ext.gone
import com.compass.mobile.framework.ext.onClick
import com.compass.mobile.framework.ext.visible
import com.compass.mobile.framework.utils.LiveDataBus
import com.compass.mobile.framework.utils.dpToPx
import com.compass.mobile.models.Attach
import com.compass.mobile.models.OrderBean
import com.compass.mobile.presenters.OrderPresenter
import com.compass.mobile.ui.activity.AddPatientActivity
import com.compass.mobile.ui.activity.OrderDetailsActivity
import com.compass.mobile.ui.dialog.CommonMessageDialog
import com.compass.mobile.ui.dialog.CustomerServiceCode
import com.compass.mobile.ui.dialog.OrderCodeDialog
import com.compass.mobile.ui.viewModel.InquiryViewModel
import com.compass.mobile.widget.MyBridgeAdapter
import getStringFromResource

/**
 * Description： 问诊单fragment
 * Date:2024/6/19 9:29
 */
class OrderFragment : BaseVBFragment<FragmentCaseItemBinding>() {
    private val inquiryViewModel: InquiryViewModel by viewModels()
    private lateinit var arrayObjectAdapter: ArrayObjectAdapter
    private var orders: MutableList<OrderBean> = mutableListOf()
    private var mPage = 1
    private var isHaveNext = true
    private var type: String = ""
    private lateinit var oderCodeDialog: OrderCodeDialog.Builder
    override fun initView(view: View, savedInstanceState: Bundle?) {
        specialColumn()


    }

    fun setSelect(type: String) {
        showLoading()
        this.type = type
        mPage = 1
        arrayObjectAdapter.clear()
        inquiryViewModel.getConsultationList(UserInfoManager.getPatientInfo()?.id, type, mPage)

    }

    override fun initData() {
        inquiryViewModel.orderDetailsLiveData.observe(this) {
            oderCodeDialog= OrderCodeDialog.Builder(requireActivity(), it, it.type, it.action,onCancelBottomClick)
            dismissLoading()
        }


        inquiryViewModel.ordersLiveData.observe(this) {
            dismissLoading()
            if (mPage == 1) {

                if (it.isNullOrEmpty()) {
                    isHaveNext(0)
                    mBinding?.emptyView?.visible()
                    mBinding?.llBelow?.gone()
                } else {
                    isHaveNext(it.size)
                    mBinding?.emptyView?.gone()
                    orders = it
                    arrayObjectAdapter.clear()
                    arrayObjectAdapter.addAll(0, orders)
                }
            } else {
                if (it.isNullOrEmpty()) {
                    isHaveNext(0)
                    mPage-- //恢复上一次的page
                    showToast("没有下一页了")
                } else {
                    isHaveNext(it.size)
                    orders = it
                    arrayObjectAdapter.clear()
                    arrayObjectAdapter.addAll(0, orders)
                }
            }
        }
        inquiryViewModel.consultationOrderLiveData.observe(this) {
            if (::oderCodeDialog.isInitialized) {
                oderCodeDialog.dismissDialog()
            }
            showToast("取消成功")
            dismissLoading()
            mPage = 1
            inquiryViewModel.getConsultationList(UserInfoManager.getPatientInfo()?.id, type, mPage)

        }
        LiveDataBus.get().with(CLINICAL_RECEPTION, Attach::class.java)
            .observe(this) {
                getConsultationList()
                getOrderDetails(it,CLINICAL_RECEPTION)

            }

        LiveDataBus.get().with(EVALUATION_ACTION, Attach::class.java)
            .observe(this) {
                getConsultationList()
                CustomerServiceCode.Builder(requireActivity(), EVALUATION_ACTION).show()
            }

        LiveDataBus.get().with(END_ACTION, Attach::class.java)
            .observe(this) {
                getConsultationList()
                getOrderDetails(it,END_ACTION)
            }

        LiveDataBus.get().with(INQUIRY_ACTION, Attach::class.java)
            .observe(this) {
                getConsultationList()
                getOrderDetails(it,INQUIRY_ACTION)
            }

//        LiveDataBus.get().with(CANCEL_ACTION, Attach::class.java)
//            .observe(this) {
//                getConsultationList()
//                getOrderDetails(it,CANCEL_ACTION)
//
//            }
        LiveDataBus.get().with(BACKSPACE_ACTION, Attach::class.java)
            .observe(this) {
                getConsultationList()
                getOrderDetails(it,BACKSPACE_ACTION)
            }
        LiveDataBus.get().with(PRESCRIPTION_ACTION, Attach::class.java)
            .observe(this) {
                getConsultationList()
                getOrderDetails(it,PRESCRIPTION_ACTION)
            }
        LiveDataBus.get().with(INSPECT_ACTION, Attach::class.java)
            .observe(this) {
                getOrderDetails(it, INSPECT_ACTION)

            }
        LiveDataBus.get().with(REFERRAL_ACTION, Attach::class.java)
            .observe(this) {
                getConsultationList()
                getOrderDetails(it,REFERRAL_ACTION)
//                OrderCodeDialog.Builder(requireActivity(), orderId, it.type, REFERRAL_ACTION).show()

            }

        inquiryViewModel.orderDetailsLiveData.observe(this) {
            oderCodeDialog= OrderCodeDialog.Builder(requireActivity(), it, it.type, it.action,onCancelBottomClick)
            oderCodeDialog.show()
            dismissLoading()
        }
    }
    private var onCancelBottomClick: OnCustomButtonClick = object : OnCustomButtonClick {
        override fun onButtonCallBack(codeType: Int, orderId: String?) {
            orderId?.let {
                cancelInquire(it)
            }?:kotlin.run {
                showToast("订单信息异常，请联系管理员")
            }

        }
    }


    private fun  getOrderDetails(attach: Attach,action:String){
        if (::oderCodeDialog.isInitialized) {
            oderCodeDialog.dismissDialog()
        }
        showLoading()
        var orderId = if (attach.id.isNullOrEmpty()) {
            attach.orderId
        } else {
            attach.id
        }
        inquiryViewModel.gePatientOrderDetails(orderId,action)
    }

    private fun isHaveNext(number: Int) {
        if (number < 10) {
            isHaveNext = false
        } else {
            mBinding?.llBelow?.visible()
            isHaveNext = true
        }
    }


    override fun intListener() {
        mBinding?.tvPrevious?.onClick {
            if (mPage > 1) {
                mPage--
                getConsultationList()
            } else {
                showToast("没有上一页了")
            }
        }

        mBinding?.tvNextPage?.onClick {
            if (isHaveNext) {
                mPage++
                getConsultationList()
            } else {
                showToast("没有下一页了")
            }
        }
    }


    private fun getConsultationList() {
        inquiryViewModel.getConsultationList(
            UserInfoManager.getPatientInfo()?.id,
            type, mPage
        )

    }

    private val onItemClickListener: OnItemClickListener = object : OnItemClickListener {
        override fun onItemClick(position: Int, view: View) {
            val item = orders[position]
//            val oderCodeDialog = CodeDialog.Builder(
//                requireActivity(),
//                MY_ORDER + UserInfoManager.getString(YD_USER_ID)
//            )
//            oderCodeDialog.show()
            showLoading()
            inquiryViewModel.gePatientOrderDetails(item.id, DETAILS_ACTION)
//            OrderDetailsActivity.start(requireContext(), item.id)
//            OrderCodeDialog.Builder(requireActivity(), item,item.type,DETAILS_ACTION).show()
        }
    }

    /**
     * 取消问诊
     */
    private fun cancelInquire(orderId: String) {
        CommonMessageDialog.Builder(requireActivity())
            .setTitle("温馨提示")
            .setMessage("确认要取消当前问诊吗?")
            .setConfirm(getStringFromResource(R.string.default_confirm))

            .setCancel(getString(R.string.default_cancel))
            .setonCancelListener {
                it?.dismiss()
            }
            .setonConfirmListener {
                it?.dismiss()
                showLoading()
                inquiryViewModel.consultationOrder(orderId)
            }.create().show()


    }


    @SuppressLint("RestrictedApi")
    fun specialColumn() {

        mBinding?.caseItem?.horizontalSpacing = dpToPx(10)
        mBinding?.caseItem?.verticalSpacing = dpToPx(10)

        arrayObjectAdapter = ArrayObjectAdapter(OrderPresenter())
        val itemBridgeAdapter = MyBridgeAdapter(
            requireContext(),
            arrayObjectAdapter, onItemClickListener
        )

        mBinding?.caseItem?.setAdapter(itemBridgeAdapter)
        mBinding?.caseItem?.setFocusScrollStrategy(BaseGridView.FOCUS_SCROLL_ITEM)
        arrayObjectAdapter.addAll(0, orders)
        FocusHighlightHelper.setupBrowseItemFocusHighlight(
            itemBridgeAdapter,
            FocusHighlight.ZOOM_FACTOR_NONE, false
        )
    }

}